package cn.csc.module.member.controller.app.browsinghistory;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.framework.excel.core.util.ExcelUtils;
import cn.csc.framework.operatelog.core.annotations.OperateLog;
import cn.csc.framework.security.core.util.SecurityFrameworkUtils;
import cn.csc.module.member.controller.app.browsinghistory.vo.*;
import cn.csc.module.member.convert.browsinghistory.ProductBrowsingHistoryConvert;
import cn.csc.module.member.dal.dataobject.browsinghistory.ProductBrowsingHistoryDO;
import cn.csc.module.member.service.browsinghistory.ProductBrowsingHistoryService;
import cn.csc.module.product.api.spu.SpuApi;
import cn.csc.module.product.api.spu.dto.SpuDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "用户 APP - 商品浏览记录")
@RestController
@RequestMapping("/member/product-browsing-history")
@Validated
public class AppProductBrowsingHistoryController {

    @Resource
    private ProductBrowsingHistoryService productBrowsingHistoryService;

    @Resource
    private SpuApi spuApi;

    @PostMapping("/createOrUpdate")
    @ApiOperation("创建或更新商品浏览记录")
    public CommonResult<BigInteger> createOrUpdate(@Valid @RequestBody AppProductBrowsingHistoryCreateReqVO createReqVO) {
        return success(productBrowsingHistoryService.createOrUpdate(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新商品浏览记录")
    public CommonResult<Boolean> updateProductBrowsingHistory(@Valid @RequestBody AppProductBrowsingHistoryUpdateReqVO updateReqVO) {
        productBrowsingHistoryService.updateProductBrowsingHistory(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除商品浏览记录")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = BigInteger.class)
    public CommonResult<Boolean> deleteProductBrowsingHistory(@RequestParam("id") BigInteger id) {
        productBrowsingHistoryService.deleteProductBrowsingHistory(id);
        return success(true);
    }

    @GetMapping("/getCurrent")
    @ApiOperation("获得当前用户的商品浏览记录")
    public CommonResult<List<AppProductBrowsingHistoryWithSpuRespVO>> getCurrent() {
        List<ProductBrowsingHistoryDO> list = productBrowsingHistoryService.getByUserId(BigInteger.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        List<BigInteger> spuIds = list.stream().map(ProductBrowsingHistoryDO::getSpuId).collect(Collectors.toList());
        List<SpuDTO> spuDTOS = spuApi.getSpuList(spuIds).getCheckedData();
        List<AppProductBrowsingHistoryWithSpuRespVO> respVOS = ProductBrowsingHistoryConvert.INSTANCE.convertList1(spuDTOS);
        Map<BigInteger, ProductBrowsingHistoryDO> historyDOMap = CollectionUtils.convertMap(list, ProductBrowsingHistoryDO::getSpuId);
        respVOS.forEach(spu -> {
            ProductBrowsingHistoryDO historyDO = historyDOMap.get(spu.getId());
            spu.setViewTime(historyDO.getViewTime());
            spu.setViewCount(historyDO.getViewCount());
        });
        //按浏览时间排序
        List<AppProductBrowsingHistoryWithSpuRespVO> collect = respVOS.stream()
                .sorted(Comparator.comparing(AppProductBrowsingHistoryWithSpuRespVO::getViewTime,Comparator.reverseOrder()))
                .collect(Collectors.toList());
        return success(collect);
    }

    @GetMapping("/list")
    @ApiOperation("获得商品浏览记录列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<AppProductBrowsingHistoryRespVO>> getProductBrowsingHistoryList(@RequestParam("ids") Collection<BigInteger> ids) {
        List<ProductBrowsingHistoryDO> list = productBrowsingHistoryService.getProductBrowsingHistoryList(ids);
        return success(ProductBrowsingHistoryConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得商品浏览记录分页")
    public CommonResult<PageResult<AppProductBrowsingHistoryRespVO>> getProductBrowsingHistoryPage(@Valid AppProductBrowsingHistoryPageReqVO pageVO) {
        PageResult<ProductBrowsingHistoryDO> pageResult = productBrowsingHistoryService.getProductBrowsingHistoryPage(pageVO);
        return success(ProductBrowsingHistoryConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出商品浏览记录 Excel")
    @OperateLog(type = EXPORT)
    public void exportProductBrowsingHistoryExcel(@Valid AppProductBrowsingHistoryExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ProductBrowsingHistoryDO> list = productBrowsingHistoryService.getProductBrowsingHistoryList(exportReqVO);
        // 导出 Excel
        List<AppProductBrowsingHistoryExcelVO> datas = ProductBrowsingHistoryConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "商品浏览记录.xls", "数据", AppProductBrowsingHistoryExcelVO.class, datas);
    }

}
